package com.woniu.service.Impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.woniu.dao.CreditOrderDao;
import com.woniu.dao.CreditRefundDao;
import com.woniu.entity.CreOrder;
import com.woniu.entity.CreRefund;
import com.woniu.service.CreditRefundService;
import com.woniu.tool.FormatDecimal;
import com.woniu.tool.MailProperties;
import com.woniu.tool.RefundUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author: Canaan
 * @description 还款实现类
 * @date: 2022/9/24 12:16
 */
@Service
public class CreditRefundServiceImpl implements CreditRefundService {

    @Autowired
    MailProperties mailProperties;
    @Autowired
    CreditRefundDao creditRefundDao;

    @Autowired
    private CreditOrderDao creditOrderDao;

    /**
     * 获取所有列表
     *
     * @param creRefund
     * @return
     */
    @Override
    public List<CreRefund> findAllRefund(CreRefund creRefund) {
        return creditRefundDao.findAllRefund(creRefund);
    }

    @Override
    public String checkEmailByUserId(int userId) {
        return creditRefundDao.checkEmailByUserId(userId);
    }

    @Override
    public boolean sendEmail(CreRefund creRefund) {
        boolean flag = false;
        int userId = creRefund.getUserId();
        String email = creditRefundDao.checkEmailByUserId(userId);
        CreRefund creRefund1 = creditRefundDao.sendEmail(creRefund);
        try {
            mailProperties.sendMail(email, "Cre金服催收消息", "尊敬的" + creRefund1.getRealName() + "你好！您在我们平台的合同(编号" + creRefund1.getContractId() + ")已逾期，请尽快还款");
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    @Override
    public int addRefund(CreRefund creRefund) {
        return creditRefundDao.addRefund(creRefund);
    }

    /**
     * 是否逾期
     *
     * @return
     */
    @Override
    public int isOutTime() {
        return creditRefundDao.isOutTime();
    }

    /**
     * 更新状态从未还款-》已逾期
     *
     * @return
     */
    @Override
    public int updateRefStatus() {
        return creditRefundDao.updateRefStatus();
    }

    /**
     * 是否还款
     *
     * @return
     */
    @Override
    public int isFinish() {
        return creditRefundDao.isFinish();
    }

    /**
     * 将已还款的变为未还款
     *
     * @return
     */
    @Override
    public int updateRefFinStatus() {
        return creditRefundDao.updateRefFinStatus();
    }

    /**
     * 订单逾期，修改订单表paymentStatus从未还款-》已逾期(2)
     *
     * @return
     */
    @Override
    public int updateOrdStatusOut() {
        return creditOrderDao.updateOrdStatusOut();
    }

    /**
     * 订单未还款，修改订单表paymentStatus从已还款-》未还款（0）
     *
     * @return
     */
    @Override
    public int updateOrdStatusFin() {
        return creditOrderDao.updateOrdStatusFin();
    }

    @Override
    @Transactional
    public AjaxResult disAffirmPay(int orderid) {
        /*
         还款信息
         */
        CreRefund creRefund = creditRefundDao.getRefund(orderid);
        CreOrder creOrder = creditOrderDao.selectCreOrderByOrderId(orderid);

        /*
        修改状态信息
         */
        creOrder.setOrderId(orderid);
        creOrder.setPaymentStatus("1");
        creRefund.setRefundStatus('1');
        int ii = creditOrderDao.updateCreOrder(creOrder);


        /*
        修改还款表信息
         */

        String paymentMethod = creRefund.getPaymentMethod();
        double applymoney = creOrder.getApplymoney();
        int loanTerm = Integer.parseInt(creRefund.getLoanTerm());
        double monthRate = creRefund.getMonthRate();
        double consultingRate = creRefund.getConsultingRate();
        double marginRate = creRefund.getMarginRate();
        // 还款次数
        int refundCount = Integer.parseInt(creRefund.getLoanTerm()) - creRefund.getRefundCount();
        /*
        等额本息
         */
        if (paymentMethod.equals("0")) {
            String[] strings = RefundUtil.calculateEqualPrincipalAndInterest(applymoney, loanTerm, refundCount, monthRate, consultingRate, marginRate);
            // 还款总额
            creRefund.setShouldTotal(Double.valueOf(strings[0]));
            // 还款次数清零
            creRefund.setRefundCount(0);
            // 还款总额
            creRefund.setShouldTotal(Double.valueOf(strings[0]));
            // 本次一次性还款金额
            creRefund.setMonthlyPayment(Double.parseDouble(strings[7]));
            // 实还金额
            creRefund.setActualTotal(Double.parseDouble(FormatDecimal.format(creRefund.getActualTotal() + Double.parseDouble(strings[7]))));
        } else if (paymentMethod.equals("1")) {
            /*
              等额本金
             */
            String[] strings = RefundUtil.calculateEqualPrincipal(applymoney, loanTerm, refundCount, monthRate, consultingRate, marginRate);
            // 还款总额
            creRefund.setShouldTotal(Double.valueOf(strings[0]));
            // 还款次数清零
            creRefund.setRefundCount(0);
            // 本次一次性还款金额
            creRefund.setMonthlyPayment(Double.parseDouble(strings[8]));
            // 实还金额
            creRefund.setActualTotal(Double.parseDouble(FormatDecimal.format(creRefund.getActualTotal() + Double.parseDouble(strings[8]))));
        }
        creditRefundDao.repayment(creRefund);
        return AjaxResult.success();
    }

    @Override
    @Transactional
    public AjaxResult affirmPayById(int userid, int orderid) {

        /*
         还款信息
         */
        CreRefund creRefund = creditRefundDao.getRefund(orderid);

        CreOrder creOrder = creditOrderDao.selectCreOrderByOrderId(orderid);

        /*
        修改状态信息
         */
        creOrder.setOrderId(orderid);
        creOrder.setPaymentStatus("1");
        creRefund.setRefundStatus('1');
        int ii = creditOrderDao.updateCreOrder(creOrder);
        

        /*
        修改还款表信息
         */

        String paymentMethod = creRefund.getPaymentMethod();
        double applymoney = creOrder.getApplymoney();
        double loanTerm = Double.parseDouble(creRefund.getLoanTerm());
        double monthRate = creRefund.getMonthRate();
        double consultingRate = creRefund.getConsultingRate();
        double marginRate = creRefund.getMarginRate();
//        等额本息
        if (paymentMethod.equals("0")) {
//            测算还款相关金额
            String[] strings = RefundUtil.calculateEqualPrincipalAndInterest(applymoney, loanTerm, monthRate, consultingRate, marginRate);
            creRefund.setShouldTotal(Double.valueOf(strings[0]));
            creRefund.setActualTotal(creRefund.getActualTotal() + Double.parseDouble(strings[3]));
            Integer refundCount = creRefund.getRefundCount();
            creRefund.setMonthlyPayment(Double.parseDouble(strings[3]));
            int refundCount1 = refundCount - 1;
            creRefund.setRefundCount(refundCount1);
            creRefund.setGrossInterest(Double.valueOf(strings[2]));
        } else if (paymentMethod.equals("1")) {
            /*
              等额本金
             */
            String[] strings = RefundUtil.calculateEqualPrincipal(applymoney, (int) loanTerm, monthRate, consultingRate, marginRate);
            creRefund.setShouldTotal(Double.valueOf(strings[0]));
//            每月应还本金
            double m = Double.parseDouble(strings[1]) / Double.parseDouble(creRefund.getLoanTerm());
            if (creRefund.getRefundCount() == Integer.parseInt(creRefund.getLoanTerm())) {
//                首月利息
                double v = Double.parseDouble(strings[1]) * creRefund.getMonthRate() / 100;
                creRefund.setGrossInterest(Double.parseDouble(FormatDecimal.format(v)));
            }
//            本次应还
            double i = m + (creRefund.getGrossInterest() - ((Integer.parseInt(creRefund.getLoanTerm()) - creRefund.getRefundCount()) * Double.parseDouble(strings[4])));
            creRefund.setMonthlyPayment(Double.parseDouble(FormatDecimal.format(i)));
            creRefund.setActualTotal(Double.parseDouble(FormatDecimal.format(i + creRefund.getActualTotal())));
            // 还款次数-1
            creRefund.setRefundCount(creRefund.getRefundCount() - 1);
        }
        creditRefundDao.repayment(creRefund);
        return AjaxResult.success();
    }
}
